<template>
  <div class="spanControl-list" style="width: 100%;margin-left: 0!important;">
    <el-card class="box-card card-head" style="margin: 0px; width: 100%; min-height: 99%">
      <div slot="header" class="clearfix">
        <span>商品类型管理</span>
      </div>
      <div class="alert-container clearfix">
        <el-alert v-for="alert in alerts.successes" :key="alert.title"
                  v-bind:title="alert.title"
                  type="success"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.infos" :key="alert.title"
                  v-bind:title="alert.title"
                  type="info"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.warnings" :key="alert.title"
                  v-bind:title="alert.title"
                  type="warning"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.errors" :key="alert.title"
                  v-bind:title="alert.title"
                  type="error"
                  show-icon>
        </el-alert>
      </div>
      <div class="text item">
        <el-form ref="goodsTypeForm" :model="goodsType" label-width="150px" :rules="rules">
          <!--<el-col :span="11">-->
          <!--<el-form-item label="名称" prop="name">-->
          <!--<file-tip content="名称"></file-tip>-->
          <!--<el-input type="input" v-model="goodsType.type"-->
          <!--placeholder="名称" clearable autosize-->
          <!--resize ="both" tabindex=1-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="11">
            <el-form-item label="商品类型" prop="type">
              <file-tip content="商品类型"></file-tip>
              <el-input type="input" v-model="goodsType.type"
                        placeholder="商品类型" clearable autosize
                        resize="both" tabindex=3
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="商家" prop="businessName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="goodsType.businessName"
                :fetch-suggestions="searchBusinessName "
                placeholder="商家"
                @select="handleSelectBusinessName"
                clearable autosize
                resize="both" tabindex="4"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <!--<el-col :span="22">-->
          <!--<el-form-item label="备注" prop="remark">-->
          <!--<file-tip content="备注"></file-tip>-->
          <!--<el-input type="textarea" v-model="goodsType.remark"-->
          <!--placeholder="备注" clearable autosize-->
          <!--resize ="both" tabindex=10000-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="11">
            <el-form-item>
              <el-button type="primary" @click="submitGoodsType()" :loading="isSubmiting"
                         v-permission:simple_goods_GoodsType_Edit>提交
              </el-button>
              <el-button type="primary" @click="backPage" style="background: #CC3300">取消</el-button>
            </el-form-item>


          </el-col>
        </el-form>
      </div>
      <div class="text item clearfix">
        <el-alert v-for="remark in alerts.remarks" :key="remark.title"
                  v-bind:title="remark.title"
                  type="info"
                  v-bind:description="remark.content">
        </el-alert>
      </div>
    </el-card>



    <span>图片123456789765432456780796543675869</span>

    <div v-for="file in fileArray">
      <img src="headerFile+file.attachmentAddr" alt="" height="200px" width="200px">
    </div>


  </div>
</template>

<script>


  import {BusinessService} from '../../simple/businessRegistration/BusinessService'
  import {GoodsTypeService} from './GoodsTypeService'
  import {d4utils} from '../../../tools/d4utils'
  import fileTip from '@/components/tip/fileTip'

  export default {
    components: {
      fileTip
    },
    data() {
      var validateIntRange = d4utils.validateFloatRange;
      var validateFloatRange = d4utils.validateFloatRange;
      var validateString = d4utils.validateString;

      return {

        fileList:[],
        fileArray:[],
        headerFile:process.env.BASE_FILE_VIEW,


        rules: {
          name: [
            {required: false, message: '请输入名称', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          type: [
            {required: true, message: '请输入商品类型', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          businessId: [
            {required: false, message: '请输入商家', trigger: 'blur'},
          ],
          businessName: [
            {required: false, message: '请输入商家', trigger: 'blur'},
          ],
          remark: [
            {required: false, message: '请输入备注', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
        },
        isSubmiting: false,
        goodsType: {},
        goodsTypeId: null,
        pickerOptionsCreateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsUpdateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        alerts: {
          remarks: [{title: "功能说明", content: "TODO: 请在这里加上功能说明"},],
          successes: [], //TODO:[{title:'消息内容'},]
          infos: [],
          warnings: [],
          errors: []
        },
      }
    },

    methods: {

      backPage() {
        debugger
        window.history.go(-1);

      },
      addAlert(message, title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        title = title ? title : message;
        this.alerts[type].unshift({title: title, content: message});
      },
      removeAlert(title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        for (var i = this.alerts[type].length - 1; i >= 0; i--) {
          delete this.alerts[type][i]
        }
      },
      submitGoodsType() {

        // this.goodsType.name=this.goodsType.type
        var refs = this.$refs;

        refs['goodsTypeForm'].validate(valid => {
          if (valid) {
            if (this.goodsType.eid)//编辑商品类型
            {
              this.updateGoodsType();
            } else//保存商品类型
            {
              this.saveGoodsType();
            }
          } else {
            return false
          }
        })
      },
      saveGoodsType()//保存商品类型
      {
        this.goodsType.name = this.goodsType.type
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在保存,请稍后...");
        GoodsTypeService.saveGoodsType(this.goodsType).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/goods/goodsType'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;

          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })
        })
      },
      updateGoodsType()//编辑商品类型
      {
        this.goodsType.name = this.goodsType.type
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在更新,请稍后...");
        GoodsTypeService.updateGoodsType(this.goodsType).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/goods/goodsType'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;
          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })

        })
      },
      findGoodsTypeForEdit(goodsTypeId)//查找商品类型
      {
        GoodsTypeService.findGoodsTypeForEdit(goodsTypeId).then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '查询商品类型出错'
          })
        })
      },
      createGoodsType()//创建新的商品类型
      {
        GoodsTypeService.createGoodsType().then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '创建新的商品类型出错'
          })
        })
      },
      prepareForEdit(goodsTypeEditDto) {
        this.goodsType = goodsTypeEditDto.goodsType;

        this.businessBusinesss = goodsTypeEditDto.businessBusinesss
      },


      searchBusinessName(queryString, cb) {
        var businessBusinesss = this.businessBusinesss;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (businessBusinesss) {
          var results = queryString ? businessBusinesss.filter(this.createFilterBusinessName(queryString)) : businessBusinesss;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findBusinesssWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            BusinessService.findBusinesssWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findBusinesssWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterBusinessName(queryString) {
        return (business) => {
          return (business.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectBusinessName(item) {
        this.goodsType.businessId = item.eid;
      },
    },
    created() {
      this.goodsTypeId = this.$route.params.goodsTypeId;
      if (this.goodsTypeId)//编辑
      {
        this.findGoodsTypeForEdit(this.goodsTypeId);
      } else//新增
      {
        this.createGoodsType();
      }
    },
  }
</script>
<style scoped lang="scss">

</style>
